package threadDemo;

/**
 * 买票案例加锁 同步
 */
public class Test15 {
    public static void main(String[] args) {
        BuyTicket b1 = new BuyTicket();
        Thread t1 = new Thread(b1,"我");
        Thread t2 = new Thread(b1,"黄牛");
        Thread t3 = new Thread(b1,"其他人");
        t1.start();
        t2.start();
        t3.start();
    }

}

class BuyTicket implements Runnable{
    private int ticket = 10;
    boolean flag = true;
    @Override
    public void run() {
        while (flag) {
            buy();
        }
    }

    private synchronized void buy() { // synchronized
        if(ticket<=0){
            flag=false;
            return;
        }
        System.out.println(Thread.currentThread().getName()+" "+ticket--);
    }
}